import { fetchUserInfo } from "./api/auth";
import { fetchFishingSpotList } from "./api/fishing-spots";
import { KEY_SPOT_ID } from "./constants/storage";

App({
  globalData: {
    testMode: false,
    userInfo: null,
    spotId: null,
    readyPromise: null, // 用于存放登录状态的Promise
  },
  async onLaunch() {
    console.log("====onLaunch page show=======");
    // 检查是否在模拟器环境
    // this.checkSimulatorEnvironment();
    // 用户登录状态
    this.globalData.readyPromise = this.checkReady();
  },
  onPageNotFound() {
    wx.redirectTo({
      url: "/pages/guide/index",
    });
  },
  changeSpotId(spotId) {
    console.log("changeSpotId====", spotId);
    this.globalData.spotId = spotId;
    wx.setStorageSync(KEY_SPOT_ID, spotId);
  },
  async initSpotData() {
    const spotList = await fetchFishingSpotList();
    if (spotList.length > 0) {
      let spotId = wx.getStorageSync(KEY_SPOT_ID) || null;
      console.log("xxxxxxxxxx====", spotId);
      // 本地没有则取第一个
      if (!spotId || !spotList.some((item) => item.id === spotId)) {
        spotId = spotList[0].id;
      }
      this.changeSpotId(spotId);
      return spotId;
    }
  },
  async checkReady() {
    const user = await fetchUserInfo();
    console.log("用户登录状态", user);
    const isLogin = !!user && user.phone;
    let isReady = true;
    if (isLogin) {
      console.log("用户已经登录");
      this.globalData.userInfo = user;
      await this.initSpotData();
    } else {
      isReady = false;
    }
    if (!isReady) {
      wx.redirectTo({
        url: "/pages/guide/index?from=launch", // 可携带来源信息
      });
      return;
    }
    console.log("====APP isReady=======", isReady);
    return isReady;
  },
  // 新的模拟器检测方法
  checkSimulatorEnvironment: function () {
    console.log("检查模拟器环境");
    const that = this;
    // 方法1：通过设备信息判断
    wx.getDeviceInfo({
      success: (res) => {
        const deviceModel = res.model.toLowerCase();
        const isSimulator =
          deviceModel.includes("simulator") ||
          deviceModel.includes("emulator") ||
          deviceModel.includes("模拟器");
        that.globalData.testMode = isSimulator;
        if (isSimulator) console.warn("当前运行在模拟器测试模式");
      },
    });
    // 方法2：备用方案 - 通过环境变量判断
    wx.getAppBaseInfo({
      success: (res) => {
        if (res.environment === "simulator") {
          that.globalData.testMode = true;
          console.warn("当前运行在模拟器测试模式");
        }
      },
    });
  },
});
